package work_pattern.rpc;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import work_pattern.Constant;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Server {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Channel channel = Constant.createChannel();
        channel.queueDeclare(Constant.RPC_QUEUE, true, false, false, null);
        // 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             *
             * @param consumerTag 消费者标签，通常是消费者在订阅队列时指定的
             * @param envelope 消息的封包信息(队列名称、交换机...)
             * @param properties 配置
             * @param body 消息内容
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                AMQP.BasicProperties replyProps = new AMQP.BasicProperties()
                        .builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                String msg = new String(body);
                System.out.println("接收到消息: " + msg);
                String response = new String("处理消息: " + msg);
                // 转发消息到回调队列
                channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes());
            }
        };
        channel.basicConsume(Constant.RPC_QUEUE, false, consumer);
        Thread.sleep(5000);
    }
}
